/*
 * Copyright 2018 the original author or authors.
 * 
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 * 
 * 
 * 
 * 
 */
 
package org.demo.util;

import java.net.InetAddress;

import javax.servlet.http.HttpServletRequest;

/**
 * ip工具
 * 
 * @author jx-air
 * @date 2018年2月24日
 * @version 1.0
 */
public abstract class ExaIpUtil {

	/**
	 * 根据请求获取ip地址，此方法适用于web
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}

		return ip;
	}

	/**
	 * 测试网络连通性，是否可以到达
	 * 
	 * @param host
	 *            主机，可以为域名(www.baidu.com)，ip（127.0.0.1）
	 * @param timeout
	 *            超时时间，单位毫秒。在此时间内是否可以到达主机
	 * @return 可以到达返回<code>true</code>，否则返回<code>false</code>
	 */
	public static boolean netReachable(String host, int timeout) {
		boolean reachable = false;
		try {
			InetAddress ip = InetAddress.getByName(host);
			reachable = ip.isReachable(timeout);
		} catch (Exception e) {
			System.out.println("网络连接超时或者网络不通");
			e.printStackTrace();
		}
		return reachable;
	}

	/**
	 * 测试网络连通性，是否可以到达，默认时间 3秒（3000毫秒）
	 * 
	 * @param host
	 *            可以为域名(www.baidu.com)，ip（127.0.0.1）
	 * @return 可以到达返回<code>true</code>，否则返回<code>false</code>
	 */
	public static boolean netReachable(String host) {
		return netReachable(host, 3000);
	}
}
